package com.cyl.XmlDemo.config;

import java.security.Principal;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

import javax.security.auth.Subject;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;

import com.cyl.XmlDemo.entity.AnonymousPrincipal;
import com.cyl.XmlDemo.entity.ShiroPrincipal;
import com.cyl.XmlDemo.utils.ShiroUtils;

public class MyHandshakeHandler extends DefaultHandshakeHandler {
	
	private static Logger logger = LoggerFactory.getLogger(MyHandshakeHandler.class);

	@Override
	protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler,
			Map<String, Object> attributes) {
		
		//shiroPrincipal 为null 即用户还没登录
		ShiroPrincipal shiroPrincipal = ShiroUtils.getPrincipal();
		Principal principal = new AnonymousPrincipal();
		if(shiroPrincipal != null){
			String uniqueName = shiroPrincipal.getUser().getUsername();
			((AnonymousPrincipal) principal).setName(uniqueName);
//			((AnonymousPrincipal) principal).setName(shiroPrincipal.getUser().getUsername());
			attributes.put("sessionId", uniqueName);
		}else{
			String uniqueName = UUID.randomUUID().toString();
			((AnonymousPrincipal) principal).setName(uniqueName);
//			attributes.put("uniqueName", uniqueName);
			
			attributes.put("sessionId", uniqueName);
		}
		return principal;
		
//		Principal principal = request.getPrincipal();
//		
//		if(principal == null){
//			principal = new AnonymousPrincipal();
//			String uniqueName = UUID.randomUUID().toString();
//			((AnonymousPrincipal) principal).setName(uniqueName);
//			attributes.put("uniqueName", uniqueName);
//		}
//
//		return principal;
	}
	
}
